const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
// 对request/response传递的参数进行解析
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const log4js = require('./utils/log4j')
// const jwt = require('jsonwebtoken')
const koajwt = require('koa-jwt')
const router = require('koa-router')()
const util = require('./utils/util')
const users = require('./routes/users')
const menus = require('./routes/menus')
const roles = require('./routes/roles')
const depts = require('./routes/depts')
const leaves = require('./routes/leaves')
const notices = require('./routes/notices')


// error handler
onerror(app)

require('./config/db')

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  log4js.info(`get params: ${JSON.stringify(ctx.request.query)}`)
  log4js.info(`post params: ${JSON.stringify(ctx.request.body)}`)
  await next().catch((err) => {
    if(err.status == '401') {
      ctx.status = 200 
      ctx.body = util.fail('token认证失败',util.CODE.AUTH_ERROR)
    } else {
      throw err; 
    }
  })
})
// 用来判断token的有效期
app.use(koajwt({secret:'imooc'}).unless({
  // 除了/user/login不验证token以外
  path:[/^\/api\/users\/login/,/^\/api\/users\/register/]
}))
router.prefix("/api")

router.get('/leave/count', (ctx) =>{
  console.log('=>', ctx.request.headers)
  // const token = ctx.request.headers.authorization.split(' ')[1]
  // const payLoad = jwt.verify(token, 'imooc')
  ctx.body = 'body'
})

router.use(users.routes(), users.allowedMethods())
router.use(menus.routes(), menus.allowedMethods())
router.use(roles.routes(), roles.allowedMethods())
router.use(depts.routes(), depts.allowedMethods())
router.use(leaves.routes(), leaves.allowedMethods())
router.use(notices.routes(), notices.allowedMethods())

app.use(router.routes(), router.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
